﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Fsb.Utility
{
    public class UrlHelper
    {
        public static string GetHost(string url)
        {
            string[] exts = { ".com", ".net", ".org", ".gov", ".tv", ".cn", ".com.cn", ".net.cn", ".gov.cn" };
            Uri uri;

            if (Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                foreach (string ext in exts)
                {
                    if (uri.Host.ToLower().EndsWith(ext))
                    {
                        string front = uri.Host.Substring(0, uri.Host.ToLower().LastIndexOf(ext));

                        int start = front.LastIndexOf(".");

                        if (start > -1)
                        {
                            return front.Substring(start + 1) + ext;
                        }
                        else
                        {
                            return front + ext;
                        }
                    }
                }
            }
            else
            {
                throw new ArgumentException(string.Format("参数{0}不是一个正确的网址。", url));
            }

            return null;
        }

        public static string GetParameter(string url, string parameterName)
        {
            Uri uri;
            if (Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                if (uri.PathAndQuery.IndexOf("?") > -1)
                {
                    string query = uri.PathAndQuery.Substring(uri.PathAndQuery.IndexOf("?") + 1);

                    foreach (string item in query.Split('&'))
                    {
                        if (item.ToLower().StartsWith(parameterName.ToLower() + "="))
                        {
                            return item.Substring(item.IndexOf("=") + 1);
                        }
                    }
                }
            }

            return null;
        }
    }
}